package com.zk.algorithm.string;

import com.zk.algorithm.annotation.Easy;
import com.zk.algorithm.annotation.LeetCodeExplore;

/**
 * @author zk
 */
@Easy
@LeetCodeExplore
public class ReverseInteger {

    // 12345 => 54321
    //
    // 12345 / 10 = 1234...5
    // 1234 / 10 = 123...4
    // 123 / 10 = 12...3
    // 12 / 10 = 1...2
    // 1 / 10 = 0...1
    public int reverse(int x) {
        if (x >= 0) {
            return reversePositive(x);
        }

        return reverseNegative(x);
    }

    private int reverseNegative(int x) {
        if (x == Integer.MIN_VALUE) {
            return 0;
        }

        return -reversePositive(-x);
    }

    private int reversePositive(int x) {
        int result = 0;

        while (x > 0) {
            int before = result;
            result = result * 10 + x % 10;
            if (isOverflow(before, result)) {
                return 0;
            }

            x /= 10;
        }

        return result;
    }

    /**
     * 是否溢出的判断
     *
     * @param before
     * @param after
     * @return
     */
    private boolean isOverflow(int before, int after) {
        return after / 10 != before;
    }

    public static void main(String...args) {
        ReverseInteger reverseInteger = new ReverseInteger();

        System.out.println(Integer.MIN_VALUE); // -21 4748 3648
        System.out.println(Integer.MAX_VALUE); // 21 4748 3647

        System.out.println(reverseInteger.reverse(12345));
        System.out.println(reverseInteger.reverse(1200));
        System.out.println(reverseInteger.reverse(-567));
        System.out.println(reverseInteger.reverse(0));
        System.out.println(reverseInteger.reverse(Integer.MAX_VALUE));
        System.out.println(reverseInteger.reverse(Integer.MIN_VALUE));
        System.out.println(reverseInteger.reverse(Integer.MIN_VALUE + 5));
        System.out.println(reverseInteger.reverse(2147483641));
    }

}
